package com.aaa.sbm.service.impl;

import com.aaa.sbm.dao.MenuDao;
import com.aaa.sbm.service.MenuService;
import com.aaa.sbm.vo.TreeNode;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @FileName: MenuServiceImpl
 * @Description:
 * @Author: 王成林
 * @CreateTime: 2025/7/8 19:21
 * @Version: 1.0.0
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuDao menuDao;
//    @Override
//    public List<TreeNode> queryTreeDate() {
//        List<TreeNode> treeNodeList = menuDao.queryAllMenu();
//        //定义返回集合（树形数据）
//        List<TreeNode> treeNodeListResult = new ArrayList<>();
//        //判断获取菜单是否为null
//        //if(treeNodeList!=null&&treeNodeList.size()>0){
//        if(!CollectionUtils.isEmpty(treeNodeList)){ //使用spring给我们提供的判断集合是否为null
//            //循环
//            for (TreeNode treeNode : treeNodeList) {
//                //查找一级菜单（parentId=0）
//                if(treeNode.getParentId()==0){
//                    treeNodeListResult.add(treeNode);
//                    //调用查找并绑定孩子方法
//                    bindChildren(treeNode,treeNodeList,new HashSet<>());
//                }
//            }
//        }
//        return treeNodeListResult;
//    }
    @Override
    public List<TreeNode> queryTreeDateByUserId(int userId) {
        List<TreeNode> treeNodeList = menuDao.queryAllMenuByUserId(userId);
        List<TreeNode> treeNodeListResult = new ArrayList<>();
        if(!CollectionUtils.isEmpty(treeNodeList)){
            for (TreeNode treeNode : treeNodeList) {
                if(treeNode.getParentId()==0){
                    treeNodeListResult.add(treeNode);
                    bindChildren(treeNode,treeNodeList,new HashSet<>());
                }
            }
        }
        return treeNodeListResult;
    }
    private void bindChildren(TreeNode currentTreeNode, List<TreeNode> treeNodeList, Set<Integer> visited){
        if (visited.contains(currentTreeNode.getId())) {
    return;
        }
        visited.add(currentTreeNode.getId());
        for (TreeNode treeNode : treeNodeList) {
            if(currentTreeNode.getId()==treeNode.getParentId()){
                List<TreeNode> children = currentTreeNode.getChildren();
                if(children==null){
                    children = new ArrayList<>();
                }
                children.add(treeNode);
                currentTreeNode.setChildren(children);
                bindChildren(treeNode,treeNodeList,visited);
            }
        }
    }
}